﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Examples;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SharpSSH.Standard;

namespace WebExamples.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class SshController : ControllerBase
    {
        public static Dictionary<string, ShellHelp> ShellHelpDic = new Dictionary<string, ShellHelp>();
        [HttpGet]
        public string ConnectShell(string ip, string name, string password)
        {
            ShellHelp shellHelp = new ShellHelp();
            bool isOk = false;
            string msg = "";
            try
            {
                (isOk, msg) = shellHelp.OpenShell(ip, name, password);
                if (isOk)
                {
                    ShellHelpDic.TryAdd(ip, shellHelp);
                    msg = "连接成功";
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                shellHelp.Close();
            }
            return msg;
        }
        [HttpGet]
        public string RunCommand(string ip, string cmd)
        {
            if (string.IsNullOrEmpty(ip) || string.IsNullOrEmpty(cmd))
            {
                return "参数不能为空";
            }
            else
            {
                if (ShellHelpDic.TryGetValue(ip, out ShellHelp shellHelp))
                {
                    if (!shellHelp.GetState())
                    {
                        bool isOk = false;
                        string msg = "";
                        (isOk,msg) =  shellHelp.AgainOpenShell();
                        if (!isOk)
                        {
                            return msg;
                        }
                    }
                    return shellHelp.Shell(cmd);
                }
                else
                {
                    return "为连接改实例";
                }
            }
        }
        [HttpGet]
        public string CloseSsh(string ip)
        {
            if (string.IsNullOrEmpty(ip))
            {
                return "参数不能为空";
            }
            else
            {
                if (ShellHelpDic.TryGetValue(ip, out ShellHelp shellHelp))
                {
                    shellHelp.Close();
                    return "关闭成功";
                }
                else
                {
                    return "为连接改实例";
                }
            }
        }
    }
}